#include <stdio.h>
#include <stdlib.h>
#include "typedef.h"
#include "TabbedFIFO.h"
#include "UART.h"

#define waitprintf(...) UART1_printfBlock(__VA_ARGS__)

void print(TabbedFIFO fifo) {
    U16 size = fifo->size + 1, cnt = 0, datasize = TabbedFIFO_getDataSize(fifo);
    S8* buffer = malloc(datasize);


    waitprintf("(%d)", fifo->size);

    TabbedFIFO_read(fifo, buffer, 0, datasize);
    if (datasize > 0) {
        waitprintf("[%.*s] ", datasize, buffer);
    } else {
        waitprintf("[] ");
    }

    if (TabbedFIFO_isEmpty(fifo)) {
        waitprintf("empty, ");
    }
    if (TabbedFIFO_isFull(fifo)) {
        waitprintf("full, ");
    }
    waitprintf("data=%d, ", datasize);
    waitprintf("free=%d, ", TabbedFIFO_getFreeSize(fifo));
    waitprintf("\r\n");
}

void minitest(TabbedFIFO test, U8 num) {
    TabbedFIFO_push(test, &num, 1);
    num++;
    TabbedFIFO_push(test, &num, 1);
    num++;
    TabbedFIFO_push(test, &num, 1);
    num++;
    TabbedFIFO_push(test, &num, 1);
    print(test);
}

void ByteTabbedFIFO_test(void) {
    TabbedFIFO test;
    S8 tab[] = "abcdefghijklmno";
    U16 a = 'A' * 256 + 'B';
    S8 out[15];

    test = TabbedFIFO_new(20);
    waitprintf("%p\r\n", test);
    TabbedFIFO_delete(test);

    test = TabbedFIFO_new(20000);
    waitprintf("%p\r\n", test);

    test = TabbedFIFO_new(10);
    waitprintf("%p\r\n", test);

    print(test);

    minitest(test, 'a');
    minitest(test, 'e');

    TabbedFIFO_push(test, &a, sizeof (a));
    print(test);
    a = 45;


    TabbedFIFO_read(test, &a, 8, 2);
    waitprintf("[%d]\r\n", a);
    print(test);

    TabbedFIFO_pop(test, out, 8);
    out[8] = 0;
    waitprintf("[%s]\r\n", out);
    print(test);

    TabbedFIFO_push(test, tab, 5);
    print(test);


    TabbedFIFO_pop(test, &a, 2);
    waitprintf("[%d]\r\n", a);
    print(test);

    TabbedFIFO_pop(test, out, 5);
    out[5] = 0;
    waitprintf("[%s]\r\n", out);
    print(test);

    TabbedFIFO_clear(test);
    print(test);

    for (a = 0; a < 5; a++) {
        while(TabbedFIFO_push(test, tab, 3)) {
            waitprintf("+++ ");
        } waitprintf("\r\n");
        print(test);
        while(TabbedFIFO_pop(test, out, 3)) {
            waitprintf("--- ");
        } waitprintf("\r\n");
        print(test);
    }


}
